<template>
  <div class="config-checkitem-container">
    <el-row>
      <el-col :span="24">
        <el-radio-group @change="toggleItemType"
                        v-model="checkItemList.item_type">
          <el-radio label="2">自由配置</el-radio>
          <el-radio label="3">数据源配置</el-radio>
        </el-radio-group>
        <el-form :inline="true"
                 label-width="100px"
                 :model="itemForm">
          <el-form-item label="表单名称">
            <el-input v-model="checkItemList.check_item_name"
                      disabled></el-input>
          </el-form-item>

          <el-button type="primary"
                     v-if="checkItemList.item_type === '2'"
                     icon="el-icon-plus"
                     @click="addCheckItem">新增</el-button>
          <!-- <el-select @change="getEntityField"
                     v-if="checkItemList.item_type==='3'"
                     v-model="choosedEntity"
                     placeholder="请选择数据源"
                     value-key="ent_id">
            <el-option v-for="item in entityList"
                       :key="item.ent_id"
                       :label="item.data_entity_name"
                       :value="item">
            </el-option>
          </el-select> -->
          <el-button type="primary"
                     v-if="checkItemList.item_type==='3' || checkItemList.item_type==='4'"
                     @click="chooseTable">选择数据表</el-button>
          <el-checkbox v-model="isChecked"
                       @change="changeCheck"
                       class="checkbox"
                       v-if="checkItemList.item_type==='3'|| checkItemList.item_type==='4'">是否为二维码业务表单</el-checkbox>
        </el-form>
      </el-col>
      <el-col :span="24"
              class="checkItem-col">
        <el-form :inline="true"
                 :inline-message="true"
                 :rules="rules"
                 :model="checkItemList"
                 ref="ruleForm">
          <el-table :data="checkItemList.item_config"
                    class="checkItem-table"
                    ref="itemTable"
                    height="600px"
                    :header-cell-style="{ background: '#f5f5f5' }"
                    border
                    align="center"
                    row-key="field_id"
                    :indent="24"
                    :default-expand-all="true"
                    :cell-style="tableCellStyle"
                    :tree-props="{ children: 'control_children' }">
            <el-table-column label="参数名"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules="rules.content_name">
                  <el-input v-model="scope.row.content_name"
                            size="mini"
                            @change="selectCode(scope, 1)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="排序"
                             width="100"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules="rules.sort">
                  <el-input v-model="scope.row.sort"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column label="参数代码"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.content_code'>
                  <el-input v-model="scope.row.content_code"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="数据类型"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.data_type'>
                  <el-select v-model="scope.row.dataType"
                             value-key="value"
                             @change="selectDataType(scope.row)"
                             size="mini">
                    <el-option v-for="item in dataTypeCodeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="最大长度"
                             align="center">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input-number v-model="scope.row.max_length"
                                   :min="1"
                                   :controls="false"
                                   size="mini"></el-input-number>
                </el-form-item>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="默认值"
                             align="center">
              <template slot-scope="scope">
                <el-form-item>
                  <el-input v-model="scope.row.default_value"
                            size="mini"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
            <el-table-column label="字段控件"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules="rules.control_type">
                  <el-select v-model="scope.row.controlType"
                             value-key="value"
                             @change="selectControlType(scope.row)"
                             size="mini">
                    <el-option v-for="item in controlTypeCodeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item"></el-option>
                  </el-select>
                </el-form-item>
                <el-button v-if="scope.row.control_type !== '26'"
                           @click="configControlDialog(scope.row, scope)"
                           type="text">配置</el-button>
                <el-button @click="addChildControl(scope.row)"
                           v-if="scope.row.control_type === '26'"
                           type="text">添加</el-button>
              </template>
            </el-table-column>
            <el-table-column label="允许复制"
                             width="120"
                             align="center"
                             prop="is_copy">
              <template slot-scope="scope">
                <el-switch :disabled="!allowCopyControl.includes(scope.row.control_type)"
                           v-model="scope.row.is_copy"
                           active-value="1"
                           inactive-value="0"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="是否必填"
                             width="120"
                             align="center">
              <template slot-scope="scope">
                <el-form-item>
                  <el-select v-model="scope.row.validate_type">
                    <el-option value="0"
                               label="否"></el-option>
                    <el-option value="1"
                               label="是"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <!-- <el-table-column align="center"
                             label="内容配置">
              <template slot-scope="scope">
                <div class="config-btn">
                  <el-button type="primary"
                             v-if="scope.row.control_type==='3' || scope.row.control_type==='15'"
                             icon="el-icon-plus"
                             @click="configDataDialog(scope.row)"
                             size="mini">配置</el-button>
                </div>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="控件配置"
                             align="center">
              <template slot-scope="scope">

                <el-form-item>
                  <el-button v-if="scope.row.controlType.content1=='array' || scope.row.controlType.content1=='object'"
                             type="primary"
                             icon="el-icon-plus"
                             size="mini"
                             @click="addChildItem(scope.row,scope.$index,scope)">配置子控件</el-button>
                  <el-button v-if="scope.row.controlType.content1=='listdrop' ||scope.row.controlType.content1=='checkbox'||scope.row.controlType.content1=='radio'"
                             type="primary"
                             icon="el-icon-plus"
                             size="mini"
                             @click="openConfig(scope.$index)">选项配置</el-button>
                  <el-input v-if="scope.row.control_type=='dictionary' "
                            v-model="scope.row.dictionary"
                            size="mini"
                            placeholder="请输入数据字典"></el-input>
                </el-form-item>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="字段校验"
                             align="center">
              <template slot-scope="scope">
                <el-form-item :rules='rules.validate_type'>
                  <el-select v-model="scope.row.validateType"
                             placeholder="请选择"
                             value-key="value"
                             @change="selectCheckType(scope.row)"
                             size="mini">

                    <el-option v-for="item in scope.row.checkTypeList"
                               :key="item.value"
                               :label="item.name"
                               :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column> -->

            <el-table-column label="操作"
                             align="center">
              <template slot-scope="scope">
                <el-tooltip content="删除"
                            placement="top">
                  <el-button type="text"
                             @click="deleteRow(scope.$index, scope)">删除</el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <div class="btn-groups">
          <el-button @click="configItem"
                     type="primary">保存</el-button>
          <el-button @click="back">取消</el-button>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="配置数据"
               :visible.sync="configDataDialogVisible">
      <el-radio-group v-model="choosedRow.origin_type"
                      @change="chooseOriginType">
        <el-radio v-for="item in dataOriginCode"
                  :key="item.code_id"
                  :label="item.value">{{ item.name }}</el-radio>
      </el-radio-group>
      <el-input v-if="choosedRow.origin_type === '1'"
                placeholder="请输入标准码"
                v-model="choosedRow.origin_data[0].val"></el-input>
      <div class="config-data-container"
           v-if="choosedRow.origin_type === '2'">
        <div v-for="(item, index) in choosedRow.origin_data"
             :key="index"
             class="config-data">
          <el-input v-model="item.key"
                    placeholder="请输入自定义数据键名">
          </el-input>
          <el-input v-model="item.val"
                    placeholder="请输入自定义数据键值">
          </el-input>
          <i @click="addConfigData"
             v-if="index === 0"
             class="fa fa-plus-circle"></i>
          <i @click="removeConfigData(index)"
             v-if="index !== 0"
             class="fa fa-minus-circle"></i>
        </div>
      </div>
      <el-input v-if="choosedRow.origin_type === '3'"
                placeholder="请输入链接地址"
                v-model="choosedRow.origin_data[0].val"></el-input>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="configDataDialogVisible = false">取 消</el-button>
        <el-button @click="configData"
                   type="primary">确 定</el-button>
      </div>
    </el-dialog>
    <ConfigControlDialog :dialogVisible.sync="configControlDialogVisible"
                         @callback="configFormCb"
                         :dialogForm="configControlDialogData"></ConfigControlDialog>

    <el-dialog title="选择数据库"
               width="60%"
               :visible.sync="dialogTableVisible"
               class="dataDialog">
      <el-row :gutter="20">
        <el-col :span="8">
          <h3>数据库列表</h3>
          <el-tree :data="entityList"
                   :props="defaultProps"
                   @node-click="handleNodeClick"></el-tree>
        </el-col>
        <el-col :span="16">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-input v-model="tableParam.table_name"
                        placeholder="请输入表名"></el-input>
            </el-col>
            <el-col :span="8">
              <el-input v-model="tableParam.table_comment"
                        placeholder="请输入表备注"></el-input>
            </el-col>
            <el-col :span="8"
                    class="flex-end">
              <el-button type="primary"
                         @click="getTableList">搜索</el-button>
              <el-button @click="reset">重置</el-button>
            </el-col>
          </el-row>
          <el-table :data="tableData.list"
                    ref="menuTable"
                    @current-change="handleSelectionChange"
                    :header-cell-style="{ background: '#f5f5f5' }"
                    border>
            <el-table-column align="center"
                             width="55">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checked"
                             @change="handleSelectionChange(scope.row)"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column property="table_name"
                             label="表名称"></el-table-column>
            <el-table-column property="table_comment"
                             label="表备注"></el-table-column>
          </el-table>
          <el-pagination @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="tableParam.page"
                         :page-size="tableParam.page_size"
                         layout="total,sizes,prev, pager, jumper"
                         background
                         small
                         :pager-count="5"
                         :total="tableData.total_count"
                         align="center">
          </el-pagination>
        </el-col>
      </el-row>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelSeltable">取 消</el-button>
        <el-button type="primary"
                   @click="saveSeltable">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
// 拼音
import "pinyin4js";
import { standardCodeApi } from "@/services/StandardCode";
import { CommonCheckApi, ConfigEntityApi } from "@/services/SystemSetting";
import ConfigControlDialog from "./components/ConfigControlDialog";
export default {
  data () {
    return {
      is_gcy: 0,
      codeType: "",
      isChecked: false,
      tableData: {
        list: [],
        total_count: 0,
      },
      resetParam: {
        is_page: 1,
        page: 1,
        page_size: 10,
        table_name: "",
        table_comment: "",
      },
      data: [],
      tableParam: {
        data_id: "",
        is_page: 1,
        page: 1,
        page_size: 10,
        table_name: "",
        table_comment: "",
      },
      dialogTableVisible: false,
      defaultProps: {
        // children: 'children',
        label: "data_name",
      },
      itemForm: {
        itemName: "",
      },
      // 表格单元格样式
      tableCellStyle: {
        // display: 'flex',
        // justifyContent: 'center',
        // alignItems: 'center'
      },
      rules: {
        param_type: [
          { required: true, message: "请选择参数分类", trigger: "change" },
        ],
        content_name: [
          { required: true, message: "请输入参数名", trigger: "blur" },
        ],
        content_code: [
          { required: true, message: "请输入参数代码", trigger: "blur" },
        ],
        data_type: [
          { required: true, message: "请选择数据类型", trigger: "change" },
        ],
        control_type: [
          { required: true, message: "请选择字段控件", trigger: "change" },
        ],
        validate_type: [
          { required: true, message: "请选择字段校验", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
      },
      // 检测值列表数据
      checkItemList: {
        check_item_id: "",
        check_item_name: "",
        item_config: [],
        // 区分自由配置模式还是数据源模式
        item_type: "2",
        ent_id: "",
        data_id: "",
        table_name: "",
      },
      // 配置数据来源时选中的行
      choosedRow: {},
      // 数据类型标准码列表
      dataTypeCodeList: [],
      // 数据类型标准码map
      dataTypeMap: new Map(),
      // 字段控件标准码源数据，因为需要根据 自由配置模式/数据源模式 切换不同的控件，所以要保留源数据
      controlTypeCode: [],
      // 字段控件标准码列表
      controlTypeCodeList: [],
      // 字段控件标准码map
      controlTypeMap: new Map(),
      // 校验类型标准码列表
      checkTypeCodeList: [],
      // 校验类型标准码map
      checkTypeMap: new Map(),
      // 配置子控件弹框是否可见
      addChildItemDialogVisible: false,
      // 配置子控件数据对象
      childItemData: [],
      // 配置数据来源弹框是否可见
      configDataDialogVisible: false,
      // 数据来源标准码
      dataOriginCode: [],
      // 配置控件弹框是否可见
      configControlDialogVisible: false,
      // 配置控件弹框数据对象
      configControlDialogData: {},
      // 当前配置数据的index
      configControlIndex: 0,
      // 允许复制的控件类型
      allowCopyControl: ["16", "17", "18", "23", "26"],

      // 当前选择的数据源
      choosedEntity: {},
      // 数据源列表
      entityList: [],
      // 检查项默认配置
      defaultCheckItemOptions: {
        content_name: "",
        content_id: "",
        control_type: "",
        validate_type: "0",
        sort: 0,
        remark: "",
        is_copy: "",
        control_children: [],
        control_cfg: {
          value_type: "1",
          content_valid_type: "no",
          min: 0,
          max: 255,
          textVal: "",
          is_copy: "0",
          float_num: "1",
          date_type: "1",
          date_fmt: "1",
          select_type: "1",
          labels: [],
          data_select_type: "1",
          data_type: "1",
          datas: [],
          data_origin_url: "",
          cascadeOptions: [],
          up_type: "1",
          num: "5",
          size: "10",
          scan_type: "1",
          content: "",
          score_way: "1",
          score: "",
          weight: "",
          location_way: "",
          user_way: "",
          search_input_default: "",
          note_value_type: "1",
          content_img: "",
          is_current_time: "",
          business_ent_data_id: "",
          control_name: "",
          data_range_type: "3",
          // 是否压缩
          is_compress: '1'
        },
      },
      checked: false
    }
  },
  components: {
    ConfigControlDialog,
  },
  methods: {
    //打开选择数据表弹窗
    chooseTable () {
      this.dialogTableVisible = true;
      this.getdataList();
    },
    //获取数据库列表
    getdataList () {
      ConfigEntityApi.getdataList({}).then((res) => {
        if (res.code === 0) {
          this.entityList = res.data;
        }
      });
    },
    //点击树
    handleNodeClick (data, item) {
      let obj = {
        data_id: data.data_id,
        data_name: data.data_name,
        data_no: data.data_no,
        table_name: "",
        ent_des: "",
        ent_id: "",
      };
      this.choosedEntity = obj;
      this.tableParam.data_id = data.data_id;
      this.getTableList();
    },
    getTableList () {
      ConfigEntityApi.getTableList({
        params: this.tableParam,
      }).then((res) => {
        if (res.code === 0) {
          this.tableData = res.data;
        }
      });
    },
    reset () {
      let reset = JSON.parse(JSON.stringify(this.resetParam));
      this.tableParam = Object.assign(this.tableParam, reset);
      this.getTableList();
    },
    //选择数据库确定
    saveSeltable () {
      if (this.choosedEntity.table_name === "") {
        this.$message.warning("请先选择数据库表");
      } else {
        this.getEntityField();
        //直接选择数据库表的时候,过滤一下二维码表单的字段控件
        this.toggleControlTypeList();
      }
    },
    //是否为二维码业务表单
    changeCheck (val) {
      if (val) {
        this.codeType = "4";
      }

      this.toggleControlTypeList();
    },
    //取消
    cancelSeltable () {
      this.dialogTableVisible = false;
      this.tableData = {
        list: [],
        total_count: 0,
      };
    },
    handleSizeChange (val) {
      this.tableParam.page_size = val;
      this.getTableList();
    },
    handleCurrentChange (val) {
      this.tableParam.page = val;
      this.getTableList();
    },
    handleSelectionChange (selection) {
      this.tableData.list.forEach((item) => {
        if (item.table_name === selection.table_name) {
          this.choosedEntity.table_name = item.table_name;
          this.choosedEntity.ent_des = item.table_comment;
          this.$set(item, "checked", true);
        } else {
          this.$set(item, "checked", false);
        }
      });
    },
    // 切换自由配置/数据源配置模式
    toggleItemType () {
      this.checkItemList.item_config = [];
      this.isChecked = false;
      this.toggleControlTypeList();
    },
    // 过滤数据
    toggleControlTypeList () {
      //二维码表单显示的字段控件
      var list = ["16", "17", "18", "19", "23", "24", "27", "36"];
      let listArr = [];
      this.controlTypeCodeList = this.controlTypeCode.filter((item) => {
        if (this.checkItemList.item_type === "2") {
          //自由配置
          return item.content3 === "1";
        } else if (this.checkItemList.item_type === "3") {
          //数据源配置
          return item.content4 === "1";
        } else {
          return true;
        }
      });
      // console.log(this.isChecked, this.codeType);
      this.controlTypeCode.forEach((item) => {
        //二维码业务表单时更换字段控件下拉框
        if (this.isChecked && this.codeType === "4") {
          list.map((id) => {
            if (item.value === id) {
              listArr.push(item);
            }
          });
          // console.log(listArr);
          this.controlTypeCodeList = listArr;
        }
      });
      // console.log(this.controlTypeCodeList, '控件列表');
    },
    // 获取数据源列表
    // getEntityList () {
    //   ConfigEntityApi.getEntityList({}).then(res => {
    //     if (res.code === 0) {
    //       console.log(res.data);
    //       this.entityList = res.data.list
    //       if (this.checkItemList.item_type === '3') {
    //         this.entityList.map((item) => {
    //           if (item.table_name === this.checkItemList.table_name) {
    //             this.choosedEntity = item
    //           }
    //         })
    //       }
    //     }
    //   })
    // },
    // 获取实体表字段信息
    getEntityField (data) {
      this.checkItemList = Object.assign(
        this.checkItemList,
        this.choosedEntity
      );
      let type = "";
      console.log(this.isChecked);
      if (this.isChecked) {
        type = this.codeType;
      } else {
        type = this.checkItemList.item_type;
      }
      console.log(type);
      ConfigEntityApi.getListName({
        params: {
          data_id: this.tableParam.data_id,
          table_name: this.choosedEntity.table_name,
          item_type: type,
        },
      }).then((res) => {
        if (res.code === 0) {
          let list = res.data.list;
          this.checkItemList.item_config = [];
          let itemConfig = [];
          list.map((item, index) => {
            let tmp = JSON.parse(JSON.stringify(this.defaultCheckItemOptions));
            tmp.sort = index + 1;
            tmp.content_code = item.real_field;
            tmp.content_name = item.field_des;
            tmp.real_field = item.real_field;
            tmp.ent_id = item.ent_id;
            tmp.field_id = item.field_id;
            tmp = Object.assign(tmp, item);
            itemConfig.push(tmp);
          });
          this.checkItemList.ent_id = list[0].ent_id;
          this.$set(this.checkItemList, "item_config", itemConfig);
          this.cancelSeltable();
        }
      });
    },
    // 添加子控件
    addChildControl (row) {
      // 获取最后一条的排序
      let sort = 1;
      let children = row.control_children;
      if (children.length > 0) {
        sort = Number(row.control_children[children.length - 1].sort) + 1;
      } else {
      }
      let item = JSON.parse(JSON.stringify(this.defaultCheckItemOptions));
      item.sort = sort;
      item.field_id = Math.floor(Math.random() * 10000) + '' + new Date().getTime()
      this.$nextTick(() => {
        // this.checkItemList.item_config[0].control_children.push(item)
        // this.$refs.itemTable.doLayout()
        children.push(item);
        // row.control_children = children
        // this.$set(row, 'control_children', children)
      });
      // console.log(this.checkItemList, '111')
    },
    back () {
      this.$router.go(-1);
    },
    // 打开配置控件弹框
    configControlDialog (row, scope) {
      // console.log(scope, 'dialog')
      this.configControlDialogVisible = true;
      row.control_cfg = row.control_cfg || {};
      this.configControlDialogData = row;
      this.configControlDialogData.is_gcy = this.is_gcy;
      this.configControlIndex = scope.$index;
    },
    // 配置控件弹框回调事件
    configFormCb (data) {
      // this.configControlDialogData = data
      // this.checkItemList.item_config[this.configControlIndex] = data
      // console.log(data, this.checkItemList, 'callback')
    },
    // 打开配置数据来源弹框
    configDataDialog (row) {
      this.choosedRow = row;
      this.configDataDialogVisible = true;
    },
    // 配置数据来源
    configData () {
      if (this.choosedRow.origin_type === "1") {
        this.choosedRow.origin_data[0].key = "code_type";
      } else if (this.choosedRow.origin_type === "3") {
        this.choosedRow.origin_data[0].key = "url";
      }
      // 判断是否填写内容
      let list = this.choosedRow.origin_data;
      // 判断key是否重复
      let dic = {};
      for (let i = 0; i < list.length; i++) {
        if (list[i]["key"] === "" || list[i]["val"] === "") {
          this.$message.warning("请完善数据配置");
          return;
        }
        if (dic[list[i]["key"]]) {
          this.$message.warning("键名不能重复");
          return;
        } else {
          dic[list[i]["key"]] = list[i]["key"];
        }
      }
      this.configDataDialogVisible = false;
    },
    // 选择数据来源类型
    chooseOriginType () {
      this.choosedRow.origin_data = [
        {
          key: "",
          val: "",
        },
      ];
    },
    // 添加自定义数据
    addConfigData () {
      this.choosedRow.origin_data.push({
        key: "",
        val: "",
      });
    },
    // 删除自定义数据
    removeConfigData (index) {
      this.choosedRow.origin_data.splice(index, 1);
    },
    // 获取配置内容
    getConfigItem () {
      return CommonCheckApi.getCheckItemContent({
        params: {
          check_item_id: this.checkItemList.check_item_id,
        },
      }).then((res) => {
        if (res.code === 0) {
          let list = [];
          list = res.data.list;
          list.map((item) => {
            item.controlType = this.controlTypeMap.get(item.control_type);
            item.field_id = item.content_id
            let children = item.control_children;
            if (children.length > 0) {
              item.control_children = children[0].list;
            }
          });
          this.checkItemList = Object.assign(this.checkItemList, res.data);
          this.checkItemList.item_config = list;
          if (res.data.item_type === "4") {
            this.isChecked = true;
            this.checkItemList.item_type = "3";
            this.codeType = res.data.item_type;
          }
          // console.log(this.checkItemList, 'get config')
        }
      });
    },
    // 修改配置内容
    configItem () {
      let flag = true;
      let checkItemList = JSON.parse(JSON.stringify(this.checkItemList));
      console.log(this.isChecked);
      if (this.isChecked) {
        checkItemList.item_type = this.codeType;
      }
      console.log(checkItemList.item_type);
      checkItemList.item_config.map((item) => {
        let children = item.control_children;
        if (item.content_name === "") flag = false;
        if (children.length > 0) {
          children.map((childItem) => {
            if (childItem.content_name === "") flag = false;
          });
          item.control_children = [{ list: children }];
        }
      });
      // console.log(flag);
      if (flag) {
        CommonCheckApi.updateCheckItemContent({
          data: checkItemList,
        }).then((res) => {
          if (res.code === 0) {
            this.$message.success("修改配置成功");
            this.$router.push({
              path: "/checkFormList",
            });
          }
        });
      } else {
        this.$message.warning("请完善数据配置");
      }
    },
    // 新增检查项
    addCheckItem () {
      // 获取最后一条的排序
      let sort = 1;
      let len = this.checkItemList.item_config.length;
      if (len > 0) {
        sort = Number(this.checkItemList.item_config[len - 1].sort) + 1;
      }
      let item = JSON.parse(JSON.stringify(this.defaultCheckItemOptions));
      item.sort = sort;
      item.field_id = Math.floor(Math.random() * 10000) + '' + new Date().getTime()
      this.checkItemList.item_config.push(item);
    },
    // 获取数据来源标准码
    getDataOriginCode () {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "originType",
          },
        })
        .then((res) => {
          //  console.log(res, 'get data type')
          if (res.code === 0 && res.data.list) {
            this.dataOriginCode = res.data.list;
            window.localStorage.setItem(
              "dataOriginCode",
              JSON.stringify(this.dataOriginCode)
            );
          }
        });
    },
    // 获取数据类型标准码
    getDataTypeCode () {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "data_type",
          },
        })
        .then((res) => {
          //  console.log(res, 'get data type')
          if (res.code === 0 && res.data.list) {
            this.dataTypeCodeList = res.data.list;
            window.localStorage.setItem(
              "dataTypeCode",
              JSON.stringify(this.dataTypeCodeList)
            );
            this.convertCodeListToMap(this.dataTypeMap, this.dataTypeCodeList);
          }
        });
    },
    // 数据类型下拉框选中事件
    selectDataType (row) {
      row.data_type = row.dataType.value;
      // 根据选中的数据类型筛选出对应的控件类型列表
      row.controlTypeList = this.controlTypeCodeList.filter((item) => {
        return row.dataType.content2.includes(item.value);
      });
      // 清空字段控件，字段校验数据
      row.control_type = "";
      row.controlType = {};
      row.validate_type = "";
      row.validateType = {};
      row.checkTypeList = [];
    },
    // 获取字段控件标准码
    getControlTypeCode () {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "field_control",
          },
        })
        .then((res) => {
          // console.log(res, 'get control type')
          if (res.code === 0 && res.data.list) {
            // for (let i = 0; i < res.data.list.length; i++) {
            //   let item = res.data.list[i]
            //   if (item.content3 !== '1') {
            //     res.data.list.splice(i, 1)
            //     i--
            //   }
            // }
            this.controlTypeCode = res.data.list;
            console.log(this.controlTypeCode);
            window.localStorage.setItem(
              "controlTypeCode",
              JSON.stringify(res.data.list)
            );
            this.convertCodeListToMap(
              this.controlTypeMap,
              this.controlTypeCode
            );
          }
        });
    },
    // 控件类型下拉框选中事件
    selectControlType (row) {
      if (row.controlType.value === "26" && !row.control_children) {
        this.$message.warning("子控件不能再选择控件组");
        row.control_type = "";
        row.controlType = {};
        row.control_children = null;

        return;
      } else {
        row.control_type = row.controlType.value;
        if (row.controlType.value !== "26" && row.control_children) {
          row.control_children = [];
        }
      }
      // console.log(row, this.checkItemList.item_config, 'select')
    },
    // 获取字段校验标准码
    getCheckTypeCode () {
      return standardCodeApi
        .getStandardCodeData({
          data: {
            code_type: "field_check",
          },
        })
        .then((res) => {
          // console.log(res, 'get control type')
          if (res.code === 0 && res.data.list) {
            this.checkTypeCodeList = res.data.list;
            window.localStorage.setItem(
              "checkTypeCode",
              JSON.stringify(this.checkTypeCodeList)
            );
            this.convertCodeListToMap(
              this.checkTypeMap,
              this.checkTypeCodeList
            );
          }
        });
    },
    // 选择校验类型下拉框选中事件
    selectCheckType (row) {
      row.validate_type = row.validateType.value;
    },
    // 将标准码列表转换为map
    convertCodeListToMap (map, codeList) {
      codeList.map((item) => {
        map.set(item.value, item);
      });
    },
    // 参数代码
    selectCode (scope, num) {
      let i = scope.$index;
      let data = scope.row.content_name;
      scope.row.content_code = PinyinHelper.getShortPinyin(data);
    },
    deleteRow (index, scope) {
      console.log(scope, "delete row");
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 根据scope.$index找到对应数据
          let len = this.checkItemList.item_config.length;
          let ind = 0;
          for (let i = 0; i < len; i++) {
            let childLen =
              this.checkItemList.item_config[i].control_children.length;
            if (ind === index) {
              this.checkItemList.item_config.splice(i, 1);
              break;
            } else if (ind + childLen >= index) {
              let target = index - ind - 1;
              this.checkItemList.item_config[i].control_children.splice(
                target,
                1
              );
              break;
            } else {
              ind += childLen;
            }
            ind++;
          }
        })
        .catch(() => { });
    },
  },
  async created () {
    // 判断是否缓存了标准码数据，是则直接使用缓存，否则请求接口
    this.checkItemList.check_item_id = this.$route.query.id;
    this.checkItemList.check_item_name = this.$route.query.name;
    this.is_gcy = this.$route.query.is_gcy;
    let dataOriginCode = window.localStorage.getItem("dataOriginCode");
    let dataTypeCode = window.localStorage.getItem("dataTypeCode");
    let controlTypeCode = window.localStorage.getItem("controlTypeCode");
    let checkTypeCode = window.localStorage.getItem("checkTypeCode");
    if (dataOriginCode) {
      this.dataOriginCode = JSON.parse(dataOriginCode);
    } else {
      await this.getDataOriginCode();
    }
    if (dataTypeCode) {
      this.dataTypeCodeList = JSON.parse(dataTypeCode);
      this.convertCodeListToMap(this.dataTypeMap, this.dataTypeCodeList);
    } else {
      await this.getDataTypeCode();
    }
    if (controlTypeCode) {
      this.controlTypeCode = JSON.parse(controlTypeCode);
      this.convertCodeListToMap(this.controlTypeMap, this.controlTypeCode);
    } else {
      await this.getControlTypeCode();
    }
    if (checkTypeCode) {
      this.checkTypeCodeList = JSON.parse(checkTypeCode);
      this.convertCodeListToMap(this.checkTypeMap, this.checkTypeCodeList);
    } else {
      await this.getCheckTypeCode();
    }
    await this.getConfigItem();
    this.toggleControlTypeList();
    // this.getEntityList()
  },
  mounted () { },
};
</script>
<style scoped lang='scss'>
.config-checkitem-container {
  padding: 20px;
  .btn-groups {
    margin-top: 20px;
    width: 100%;
    text-align: center;
  }
  .config-btn {
    text-align: center;
  }
  .checkItem-table {
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .el-table {
    margin-top: 20px;
  }
}
.el-radio-group {
  margin-bottom: 20px;
}
.config-data-container {
  height: 400px;
  overflow-y: scroll;
  .config-data {
    display: flex;
    align-items: center;
    .el-input {
      width: 300px;
      margin-right: 20px;
      margin-bottom: 20px;
    }
    .fa {
      font-size: 30px;
      position: relative;
      top: -11px;
      cursor: pointer;
    }
  }
}
.dataDialog {
  h3 {
    display: block;
    padding: 20px;
    border: solid 1px #e6e6e6;
  }
}
.dataDialog /deep/.el-tree {
  height: 400px;
  border: solid 1px #e6e6e6;
}
.dataDialog /deep/ .el-tree-node__content {
  padding: 20px;
}
.checkbox {
  margin-left: 10px;
}
</style>

